from Products.CMFCore.utils import getToolByName
from Products.SIGFS.config import *
from Products.SIGFS.AppConfig import *
from Products.SIGFS.Extensions.install_taxonomy import *
from Products.ExternalMethod.ExternalMethod import ExternalMethod

PERMISSION_LIST = (
    {
        'permission' : 'Add portal member',
        'roles' : ['Manager'],
        'acquire' : False,
    },
    {
        'permission' : 'Add portal messages',
        'roles' : ['Manager', 'Reviewer', 'Owner', 'Member', 'Authenticated'],
        'acquire' : False,
    },
    {
        'permission' : 'Change portal messages',
        'roles' : ['Manager', 'Reviewer', 'Owner', 'Member', 'Authenticated'],
        'acquire' : False,
    },
    {
        'permission' : 'View portal messages',
        'roles' : ['Manager', 'Reviewer', 'Owner', 'Member', 'Authenticated'],
        'acquire' : False,
    },
    {
        'permission' : 'SIGFS: Add Proposta',
        'roles' : ['Manager', 'MembroProposta'],
        'acquire' : False,
    },
    {
        'permission' : 'Add portal content',
        'roles' : ['Manager', 'Owner','Member','Authenticated', 'MembroProposta'],
        'acquire' : False,
    },
##     {
##         'permission' : 'Access contents information',
##         'roles' : ['Manager', 'Owner','Member','Authenticated', 'MembroProposta'],
##         'acquire' : False,
##     },
##     {
##         'permission' : 'View',
##         'roles' : ['Manager', 'Owner','Member','Authenticated', 'MembroProposta'],
##         'acquire' : False,
##     }
##     ,

    
)

LISTA_ACOES_FORM_CONTROLLER = [
    {
        'template' : 'validate_integrity',
        'status' : 'success',
        'context' : 'Atividade',
        'button' : None,
        'action' : 'traverse_to',
        'expression' : 'string:salvar_atividade',
    },
    {
        'template' : 'validate_integrity',
        'status' : 'success',
        'context' : 'TermoReferencia',
        'button' : None,
        'action' : 'traverse_to',
        'expression' : 'string:salvar_termo',
    },
    {
        'template' : 'validate_integrity',
        'status' : 'success',
        'context' : 'ChamadaPublica',
        'button' : None,
        'action' : 'traverse_to',
        'expression' : 'string:salvar_chamada_publica',
    },
    {
        'template' : 'validate_integrity',
        'status' : 'success',
        'context' : 'CartaConvite',
        'button' : None,
        'action' : 'traverse_to',
        'expression' : 'string:salvar_carta_convite',
    },
    {
        'template' : 'validate_integrity',
        'status' : 'success',
        'context' : 'Encomenda',
        'button' : None,
        'action' : 'traverse_to',
        'expression' : 'string:salvar_encomenda',
    },
    {
        'template' : 'validate_integrity',
        'status' : 'success',
        'context' : 'Aditivo',
        'button' : None,
        'action' : 'traverse_to',
        'expression' : 'string:salvar_aditivo',
    },
    {
        'template' : 'validate_integrity',
        'status' : 'success',
        'context' : 'Reuniao',
        'button' : None,
        'action' : 'traverse_to',
        'expression' : 'string:salvar_reuniao',
    },
]

def install(self):
    portal = self
    setup_permissions(portal)
    setupFormController(portal)
    setupConfigletPreferences(portal)
    setupMembersFolder(portal)
    setupWorkflow(portal)
    setupPortal(portal)
    setupSlots(portal)
    setupIndex(portal)
    addTaxonomy(portal)
    deleteAction(portal)
    addActions(portal)
    addGroups(portal)
    setupCalendar(portal)
    setupLanguages(portal)
    setupMemberdata(portal)
    setupProperties(portal)
    setupPublicator(portal)
    setupRSS(portal)
    setupSkin(portal)
    setupTypes(portal)

def setup_permissions(portal):
    for p in PERMISSION_LIST:
        portal.manage_permission(p['permission'], roles=p['roles'], acquire=p['acquire'])

def setupFormController(portal):
    portal_form_controller = getToolByName(portal, 'portal_form_controller')
    for action in LISTA_ACOES_FORM_CONTROLLER:
        portal_form_controller.addFormAction(action['template'],
                                             action['status'],
                                             action['context'],
                                             action['button'],
                                             action['action'],
                                             action['expression'])

def setupConfigletPreferences(portal):
    portal.portal_controlpanel.registerConfiglet(id = 'sigfs_personalize_form',
                                                 name = 'Preferências dos Usuários do SIGFS',
                                                 action = 'string:${portal_url}/sigfs_personalize_form',
                                                 permission = 'Set own properties',
                                                 category = 'Member',
                                                 appId = PROJECTNAME,
                                                 imageUrl = 'user.gif',
                                                 )

def setupMembersFolder(portal):
    members = portal.Members
    if members.hasProperty('right_slots'):
        members.manage_delProperties(['right_slots'])
    members.manage_changeProperties(title='Membros')

def setupWorkflow(portal):
    '''Instalação do Workflow'''
    productname = 'SIGFS'
    portal_workflow = getToolByName(portal, 'portal_workflow')

    ourProductWorkflow = ExternalMethod('temp', 'temp',
                                        productname+'.'+'sigfs_workflow',
                                        'createsigfs_workflow')
    workflow = ourProductWorkflow(portal, 'sigfs_workflow')
    if 'sigfs_workflow' in portal_workflow.listWorkflows():
        print >> out, 'sigfs_workflow already in workflows.'
    else:
        portal_workflow._setObject('sigfs_workflow', workflow)

    portal_workflow.setDefaultChain('sigfs_workflow')

def setupPortal(portal):
    portal.manage_changeProperties(title='Sistema de Informações Gerenciais dos Fundos Setoriais',
                                   email_from_address='cadu@ibict.br',
                                   email_from_name='Administrador do Portal')
    if not portal.hasProperty('content_support_email'):
        portal._setProperty('content_support_email', 'cadu@ibict.br', 'string')

def setupSlots(portal):
    left_slots =  ()
    portal._setPropValue('left_slots', left_slots)
    right_slots = ('here/portlet_navegacao_portal/macros/portlet', \
                   'here/portlet_review/macros/portlet', \
                   'here/portlet_member/macros/portlet', \
                   'here/portlet_activeusers21/macros/portlet', \
                   'here/portlet_message_list21/macros/portlet', \
                   'here/portlet_recent/macros/portlet',)
    portal._setPropValue('right_slots', right_slots)

def setupIndex(portal):
    portal_types = getToolByName(portal, 'portal_types')
    front_page = getattr(portal, 'front-page', None)
    if front_page is not None: 
        portal._delObject('front-page')

    portal_types['Plone Site'].manage_changeProperties(view_methods = ['front-page', 'folder_listing', 'folder_summary_view', 'folder_tabular_view', 'atct_album_view'])

def addTaxonomy(portal):
    createTaxonomy(portal)

def deleteAction(portal):
    portal_actions = getToolByName(portal, 'portal_actions')
    idx = 0
    for action in portal_actions.listActions():
        if action.getId() == 'index_html':
            portal_actions.deleteActions((idx,))
            break
        idx += 1

def addActions(portal):
    portal_actions = getToolByName(portal, 'portal_actions')
    portal_actions.addAction(id='mct', name='O MCT', action='string:http://www.mct.gov.br/index.php/content/view/105.html', condition='', permission='View', category='portal_tabs', visible=1)

    portal_actions.addAction(id='indicadores', name='Indicadores', action='string:http://www.mct.gov.br/index.php/content/view/740.html', condition='', permission='View', category='portal_tabs', visible=1)

    portal_actions.addAction(id='legislacao', name='Legislacao', action='string:http://www.mct.gov.br/index.php/content/view/723.html', condition='', permission='View', category='portal_tabs', visible=1)

    portal_actions.addAction(id='fontes-de-financiamento', name='Fontes de Financiamento', action='string:http://www.mct.gov.br/index.php/content/view/724.html', condition='', permission='View', category='portal_tabs', visible=1)
  
    portal_actions.addAction(id='unidades-de-pesquisa', name='Unidades de Pesquisa', action='string:http://www.mct.gov.br/index.php/content/view/741.html', condition='', permission='View', category='portal_tabs', visible=1)

def addGroups(portal):
    portal_groups = getToolByName(portal, 'portal_groups')
    groups = [i.getGroupName() for i in portal_groups.listGroups()]

    added_groups = [
        ['CGAeronautico', {'title':'Comitê Gestor CT-Aeronáutico', 'description':'Grupo do Comitê Gestor do Fundo Setorial Aeronáutico', 'email':'ct-aero@mct.gov.br'}],
        ['CGAgronegocio', {'title':'Comitê Gestor CT-Agronegócio', 'description':'Grupo do Comitê Gestor do Fundo Setorial do Agronegócio', 'email':'ct-agro@mct.gov.br'}],
        ['CGAmazonia', {'title':'Comitê Gestor CT-Amazônia', 'description':'Grupo do Comitê Gestor do Fundo Setorial da Amazônia', 'email':'ct-amzonia@mct.gov.br'}],
        ['CGBiotecnologia', {'title':'Comitê Gestor CT-Biotecnologia', 'description':'Grupo do Comitê Gestor do Fundo Setoria de Biotecnologia', 'email':'ct-biotec@mct.gov.br'}],
        ['CGEnerg', {'title':'Comitê Gestor CT-Energ', 'description':'Grupo do Comitê Gestor do Fundo Setorial de Energia', 'email':'ct-energ@mct.gov.br'}],
        ['CGEspacial', {'title':'Comitê Gestor CT-Espacial', 'description':'Grupo do Comitê Gestor do Fundo Setorial Espacial', 'email':'ct-espacial@mct.gov.br'}],
        ['CGHidro', {'title':'Comitê Gestor CT-Hidro', 'description':'Grupo do Comitê Gestor do Fundo Setorial de Recursos Hídricos', 'email':'ct-hidro@mct.gov.br'}],
        ['CGInfo', {'title':'Comitê Gestor CT-Info', 'description':'Grupo do Comitê Gestor do Fundo Setorial de Tecnologia da Informação', 'email':'ct-info@mct.gov.br'}],
        ['CGInfra', {'title':'Comitê Gestor CT-Infra', 'description':'Grupo do Comitê Gestor do Fundo Setorial de Infra-Estrutura', 'email':'ct-infra@mct.gov.br'}],
        ['CGMineral', {'title':'Comitê Gestor CT-Mineral', 'description':'Grupo do Comitê Gestor do Fundo Setorial de Recursos Minerais', 'email':'ct-mineral@mct.gov.br'}],
        ['CGPetro', {'title':'Comitê Gestor CT-Petro', 'description':'Grupo do Comitê Gestor do Fundo Setorial de Petróleo e Gás Natural', 'email':'ct-petro@mct.gov.br'}],
        ['CGSaude', {'title':'Comitê Gestor CT-Saúde', 'description':'Grupo do Comitê Gestor do Fundo Setorial de Saúde', 'email':'ct-saude@mct.gov.br'}],
        ['CGTransporte', {'title':'Comitê Gestor CT-Transporte', 'description':'Grupo do Comitê Gestor do Fundo Setorial de Transportes Terrestres e Hidroviários', 'email':'ct-transporte@mct.gov.br'}],
        ['CGTransporteAquaviario', {'title':'Comitê Gestor CT-Transporte Aquaviário e de Construção Naval', 'description':'Grupo do Comitê Gestor do Fundo Setorial de Transporte Aquaviário e de Construção Naval', 'email':'ct-aquaviario@mct.gov.br'}],
        ['CGVerdeAmarelo', {'title':'Comitê Gestor CT-Verde Amarelo', 'description':'Grupo do Comitê Gestor do Fundo Setorial Verde Amarelo', 'email':'ct-fva@mct.gov.br'}],
        ['CCAscofs', {'title':'Comitê de Coordenação da ASCOFS', 'description':'Grupo do Comitê de Coordenação da ASCOFS', 'email':''}],
]

    for l in [i for i in added_groups if i[0] not in groups]:
        data = l[1]
        portal_groups.addGroup(l[0], title=data['title'], description=data['description'], email=data['email'])

def setupCalendar(portal):
    portal_calendar = getToolByName(portal, 'portal_calendar')
    types = ('Event', 'Reuniao', 'Atividade',)
    portal_calendar.calendar_types = tuple(types)

def setupLanguages(portal):
    languages = getToolByName(portal, 'portal_languages')
    defaultLanguage = 'pt-br'
    supportedLanguages = ['pt-br']
    languages.manage_setLanguageSettings(defaultLanguage, supportedLanguages,
                                         setCookieN=True, setRequestN=False,
                                         setPathN=True, setForcelanguageUrls=True,
                                         setAllowContentLanguageFallback=False,
                                         setUseCombinedLanguageCodes=True,
                                         startNeutral=True, displayFlags=False)

def setupMemberdata(portal):
    portal_memberdata = getToolByName(portal, 'portal_memberdata')
    if not portal_memberdata.hasProperty('telefone'):
        portal_memberdata._setProperty('telefone', '', 'string')
    if not portal_memberdata.hasProperty('orgao'):
        portal_memberdata._setProperty('orgao', '', 'string')
    if not portal_memberdata.hasProperty('funcao'):
        portal_memberdata._setProperty('funcao', '', 'string')
    if not portal_memberdata.hasProperty('estado'):
        portal_memberdata._setProperty('estado', '', 'string')
    if not portal_memberdata.hasProperty('formacao'):
        portal_memberdata._setProperty('formacao', '', 'string')
    if not portal_memberdata.hasProperty('atividade'):
        portal_memberdata._setProperty('atividade', '', 'string')
    if not portal_memberdata.hasProperty('cidade'):
        portal_memberdata._setProperty('cidade', '', 'string')
    if not portal_memberdata.hasProperty('pais'):
        portal_memberdata._setProperty('pais', '', 'string')
    if not portal_memberdata.hasProperty('instituicao'):
        portal_memberdata._setProperty('instituicao', '', 'string')
    if not portal_memberdata.hasProperty('sigla'):
        portal_memberdata._setProperty('sigla', '', 'string')
    if not portal_memberdata.hasProperty('instituto'):
        portal_memberdata._setProperty('instituto', '', 'string')
    if not portal_memberdata.hasProperty('departamento'):
        portal_memberdata._setProperty('departamento', '', 'string')
    if not portal_memberdata.hasProperty('outra'):
        portal_memberdata._setProperty('outra', '', 'string')
    if not portal_memberdata.hasProperty('primeira_visita'):
        portal_memberdata._setProperty('primeira_visita', '', 'boolean')
    if not portal_memberdata.hasProperty('fundo'):
        portal_memberdata._setProperty('fundo', '', 'string')
    if not portal_memberdata.hasProperty('projeto'):
        portal_memberdata._setProperty('projeto', '', 'boolean')
    if not portal_memberdata.hasProperty('evento'):
        portal_memberdata._setProperty('evento', '', 'boolean')

def setupProperties(portal):
    portal_properties = getToolByName(portal, 'portal_properties')
    if not portal_properties.site_properties.hasProperty('validate_email'):
        portal_properties.site_properties._setProperty('validate_email', '', 'boolean')
    portal_properties.site_properties.validate_email = (True)
    portal_properties.site_properties.allowAnonymousViewAbout = (False)
    portal_properties.site_properties.default_language = 'pt-br'
    portal_properties.site_properties.localTimeFormat = '%d/%m/%Y'
    portal_properties.site_properties.localLongTimeFormat = '%d/%m/%Y %H:%M'
    portal_properties.site_properties.disable_folder_sections = (True)
    portal_properties.navtree_properties.includeTop = (False)
    portal_properties.navtree_properties.name = ('Portal dos Fundos Setoriais')
    portal_properties.navtree_properties.idsNotToList = ('Members',)
    
    if not portal_properties.hasProperty('portal_sigfs_properties'):
        portal_properties.manage_addPropertySheet('portal_sigfs_properties','Propriedades do SIGFS')
        if not portal_properties.portal_sigfs_properties.hasProperty('funcao'):
            portal_properties.portal_sigfs_properties._setProperty('funcao', ['Presidente', 'Secretário Técnico', 'Membro', 'Secretária', 'Suplente'], 'lines')
        if not portal_properties.portal_sigfs_properties.hasProperty('estado'):
            portal_properties.portal_sigfs_properties._setProperty('estado', 
                               ['AC;Acre','AL;Alagoas','AP;Amapá', 'AM;Amazonas', 'BA;Bahia', 'CE;Ceará',\
                                'DF;Distrito Federal','ES;Espírito Santo','GO;Goiás','MA;Maranhão',\
                                'MT;Mato Grosso','MS;Mato Grosso do Sul','MG;Minas Gerais','PA;Pará',\
                                'PB;Paraíba','PR;Paraná','PE;Pernambuco','PI;Piauí','RJ;Rio de Janeiro',\
                                'RN;Rio Grande do Norte','RS;Rio Grande do Sul','RO;Rondônia',\
                                'RR;Roraima','SC;Santa Catarina','SP;São Paulo','SE;Sergipe','TO;Tocantins'], 'lines')
        if not portal_properties.portal_sigfs_properties.hasProperty('formacao'):
            portal_properties.portal_sigfs_properties._setProperty('formacao', 
                               ['1;2° Grau','2;Graduando','3;Graduado', '4;Especialista', '5;Mestrando', '6;Mestre',\
                                '7;Doutorando','8;Doutor','9;Pós Doutor','10;Empresário',\
                                '11;Estudante sem vínculo empregatício'], 'lines')
        if not portal_properties.portal_sigfs_properties.hasProperty('atividade'):
            portal_properties.portal_sigfs_properties._setProperty('atividade', 
                               ['1;Professor','2;Pesquisador','3;Professor/Pesquisador', '4;Gestor/Administrador',\
                                '5;Profissional de Nível Superior'], 'lines')

        if not portal_properties.portal_sigfs_properties.hasProperty('fundos'):
            portal_properties.portal_sigfs_properties._setProperty('fundos', 
                               ['1;CT-Aeronáutico','2;CT-Agronegócio','3;CT-Amazônia', \
                                '4;CT-Biotecnologia', '5;CT-Energ', '6;CT-Espacial', '7;CT-Hidro', \
                                '8;CT-Info', '9;CT-Infra', '10;CT-Mineral', '11;CT-Petro', '12;CT- Saúde',\
                                '13;CT-Transporte', '14;CT-Transporte Aquaviário e de Construção Naval', \
                                '15;CT-Verde Amarelo', '16;Funttel'], 'lines')

def setupPublicator(portal):
    portal_publicator = getToolByName(portal, 'portal_publicator')
    portal_publicator.deletePublicationBoxes(['news'])

    portal_publicator.addPublicationBox(id='noticia',
                           name='Notícias',
                           search_states=['published'],
                           content_type=['News Item'],
                           n_items=3)

def setupRSS(portal):
    rss = getToolByName(portal, 'portal_syndication')
    idx = 0
    for action in rss.listActions():
        if action.getId() == 'syndication':
            rss.deleteActions((idx,))
            break
        idx += 1

    rss.addAction('syndication', 'Syndication', 'string:${folder_url}/synPropertiesForm', 'python: folder is object and portal.portal_syndication.isSiteSyndicationAllowed()', 'Manage Properties', 'object', 1)
    rss.editProperties(isAllowed=1)

    portal_fundos = getattr(portal, 'portal_fundos', None)
    noticias = getattr(portal_fundos, 'noticias', None)
    if noticias.portal_syndication.isSiteSyndicationAllowed():
        noticias.portal_syndication.enableSyndication(noticias)

def setupSkin(portal):
    portal_skins = getToolByName(portal, 'portal_skins')
    path = portal_skins.getSkinPath('Plone Default')
    path = [elem.strip() for elem in path.split(',') if elem != '.svn']
    path = ','.join(path)
    portal_skins.addSkinSelection('SIGFS', path)
    portal_skins.manage_properties(default_skin = 'SIGFS',
                                   request_varname = 'plone_skin',
                                   del_skin = 0, 
                                   chosen = [] )

    css = getToolByName(portal, 'portal_css')
    css.manage_addStylesheet(id='sigfsCustom.css', media='all', enabled=True)

def setupTypes(portal):
    portal_types = getToolByName(portal, 'portal_types')
    portal_types['Plone Site'].filter_content_types = True
    addable_types=['Folder']
    portal_types['Plone Site'].allowed_content_types = addable_types
    portal_types['Event'].global_allow = False

def uninstall(self):
    portal = self
    locked_ids = ('portal_fundos', 'fundos')
    po = self.portal_quickinstaller.SIGFS.portalobjects
    for id in locked_ids:
        if id in po:
            po.remove(id)

    rss = getToolByName(portal, 'portal_syndication')
    idx = 0
    for action in rss.listActions():
        if action.getId() == 'syndication':
            rss.deleteActions((idx,))
            break
        idx += 1
    portal_fundos = getattr(portal, 'portal_fundos', None)
    noticias = getattr(portal_fundos, 'noticias', None)
    if noticias.portal_syndication.isSiteSyndicationAllowed():
        noticias.portal_syndication.disableSyndication(noticias)

    portal_types = getToolByName(portal, 'portal_types')
    portal_types['Plone Site'].global_allow = True
    portal_types['Plone Site'].filter_content_types = False

    portal_controlpanel = getToolByName(portal,'portal_controlpanel')
    portal_controlpanel.unregisterConfiglet('sigfs_personalize_form')

    portal_properties = getToolByName(portal, 'portal_properties')
    portal_properties._delObject('portal_sigfs_properties')

    portal_publicator = getToolByName(portal, 'portal_publicator')
    portal_publicator.deletePublicationBoxes(['noticia'])
